/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2024-08-31
 * Time: 17:30
 */


public class Test2 {
    // 删除单链表中的所有元素
    public ListNode removeElements(ListNode head, int val) {
        if(head == null) {
            return null;
        }
        ListNode prev = head;
        ListNode cur = head.next;
        while(cur != null) {
            if(cur.val == val) {
                prev.next = cur.next;
            }else {
                prev = prev.next;
            }
            cur = cur.next;
        }
        if(head.val == val) {
            head = head.next;
        }
        return head;
    }
    // 逆置单链表
    public ListNode reverseList(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode cur = head.next;
        head.next = null;
        while(cur != null) {
            ListNode curNext = cur.next;
            cur.next = head;
            head = cur;
            cur = curNext;
        }
        return head;
    }
    // 求链表的中间节点
    public ListNode middleNode(ListNode head) {
        if(head == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
    // 获取链表倒数第K个节点
    public ListNode FindKthToTail(ListNode head,int k) {
        if(k <= 0) {
            return null;
        }
        if(head == null) {
            return null;
        }
        ListNode slow = head;
        ListNode fast = head;
        while(k - 1 != 0) {
            fast = fast.next;
            k--;
        }
        while(slow.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
    // 合并两个有序链表
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if(list1 != null && list2 == null) {
            return list1;
        }
        if(list1 == null && list2 != null) {
            return list2;
        }
        if(list1 == null && list2 == null) {
            return null;
        }
        ListNode newHead = new ListNode();
        ListNode head = newHead;
        while(list1 != null && list2 != null) {
            if(list1.val < list2.val) {
                head.next = list1;
                head = list1;
                list1 = list1.next;
            }else {
                head.next = list2;
                head = list2;
                list2 = list2.next;
            }
        }
        if(list1 == null) {
            head.next = list2;
        }
        if(list2 == null) {
            head.next = list1;
        }
        return newHead.next;
    }
    public static void main(String[] args) {

    }
}
